#include "CCacheCtl.h"
#include "CCmd.h"
#include "CCFile.h"
#include "CConfig.h"

#include <windows.h>

CCacheCtl::CCacheCtl( CCmd * cmd, CConfig * config ):
		m_cmd(cmd)
	,	m_config(config)
{
}


void CCacheCtl::execute()
{
	PROCESS_INFORMATION processInfo;
	STARTUPINFO startupInfo;
	memset(&processInfo, 0, sizeof(processInfo)); 
	memset(&startupInfo, 0, sizeof(startupInfo)); 
	ZeroMemory(&startupInfo, sizeof(startupInfo));
	startupInfo.cb = sizeof startupInfo ; 
	
	std::string commandLine = m_cmd->commandLine();
	

	LPSTR lpCmdLine = _strdup(commandLine.c_str());

	std::cout << "current path:" << bfs::current_path().string() << std::endl;

	CCFile * file = m_cmd->input();
	if( m_config->isTracked( file ) )
	{
		std::cout << file->filePath() << " is tracked!";
		bfs::path objPath = bfs::path( cacheDir() /= file->fileOutputPath()  );
		bfs::copy_file( objPath /= "obj.o" , m_cmd->output(), bfs::copy_option::overwrite_if_exists );
	}
	else
	{
		if(CreateProcess(NULL,lpCmdLine,NULL,NULL,NULL,NULL,NULL,NULL, &startupInfo, &processInfo))
		{
			::WaitForSingleObject(processInfo.hProcess,INFINITE);

			DWORD exitCode;
			::GetExitCodeProcess(processInfo.hProcess,&exitCode);

			std::cout << "process exit code:" << exitCode;
			std::cout << "Adding file:" << file->filePath()  << std::endl;
			std::cout << "Output obj:" << m_cmd->output() << std::endl;
			if( exitCode == 0)
			{
				std::cout << "Adding file:" << file->filePath() << " success" << std::endl;
				m_config->addFile( file );
				bfs::path objPath = bfs::path( cacheDir() /= file->fileOutputPath() );
				bfs::copy_file( objPath /= "obj.o" , m_cmd->output(), bfs::copy_option::overwrite_if_exists );
			}

			CloseHandle(processInfo.hThread);
			CloseHandle(processInfo.hProcess);	
		}
	}


					
}
